package summary;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @Author: 海琳琦
 * @Date: 2022/3/13 15:30
 * https://leetcode-cn.com/problems/average-of-levels-in-binary-tree/
 */
public class Title637 {

    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        public TreeNode() {
        }

        public TreeNode(int val) {
            this.val = val;
        }

        public TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public static List<Double> averageOfLevels(TreeNode root) {
        List<Double> result = new ArrayList<>();
        if (root == null) {
            return result;
        }
        LinkedList<TreeNode> list = new LinkedList<>();
        list.offer(root);
        while (!list.isEmpty()) {
            int size = list.size();
            Double aveValue = 0.0;
            for (int i = 0; i < size; i++) {
                TreeNode pop = list.pop();
                aveValue += pop.val;
                if (pop.left != null) {
                    list.add(pop.left);
                }
                if (pop.right != null) {
                    list.add(pop.right);
                }
            }
            aveValue /= size;
            result.add(aveValue);
        }
        return result;
    }

    public List<Double> averageOfLevels1(TreeNode root) {
        List<Double> result = new ArrayList<>();
        List<Double> sum = new ArrayList<>();
        List<Double> count = new ArrayList<>();
        dfs(root, sum, count, 0);
        for (int i = 0; i < sum.size(); i++) {
            result.add(sum.get(i) / count.get(i) );
        }
        return result;
    }

    private void dfs(TreeNode root, List<Double> sum, List<Double> count, int depth) {
        if (root == null) {
            return;
        }
        if (sum.size() == depth) {
            sum.add((double)root.val);
            count.add(1.0);
        }else{
            sum.set(depth, sum.get(depth) + root.val);
            count.set(depth, count.get(depth) + 1);
        }
        depth++;
        dfs(root.left, sum, count, depth);
        dfs(root.right, sum, count, depth);
    }


    public static void main(String[] args) {
        TreeNode root = new TreeNode(3);
        root.left = new TreeNode(9);
        root.right = new TreeNode(20);
        root.right.left = new TreeNode(15);
        root.right.right = new TreeNode(7);
        averageOfLevels(root);
    }
}
